package com.jbit.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jbit.pojo.Employee;
import com.jbit.pojo.MailLog;
import com.jbit.pojo.constant.MailConstant;
import com.jbit.service.IEmployeeService;
import com.jbit.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @program: yeb
 * @description: 邮件发送定时任务
 * @author: Mr.Li
 * @create: 2021-12-14 14:51
 **/
@Component
public class MailTask {

    @Autowired
    private IMailLogService mailLogService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 邮件发送十秒执行一次
     */
    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask() {
        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>().eq("status", 0).lt("tryTime", LocalDateTime.now()));
        list.forEach(mailLog -> {
            //如果重试次数超过三次，标记为失败
            if (mailLog.getCount() >= 3) {
                mailLogService.update(new UpdateWrapper<>(mailLog).set("status", 2).eq("msgId", mailLog.getMsgId()));
            }else{
                mailLogService.update(new UpdateWrapper<>(mailLog).set("count", mailLog.getCount() + 1).set("tryTime", LocalDateTime.now().plusMinutes(MailConstant.MSG_TIMEOUT)).eq("msgId", mailLog.getMsgId()));
                Employee emp = employeeService.getEmployee(mailLog.getEid()).get(0);
                rabbitTemplate.convertAndSend(MailConstant.MAIL_EXCHANGE_NAME, MailConstant.MAIL_ROUTING_KEY_NAME, emp, new CorrelationData(mailLog.getMsgId()));
            }
        });
    }
}
